//
//  MallInLiveViewController.m
//  CYWFrame
//
//  Created by Macx on 2018/8/31.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "MallInLiveViewController.h"
#import "MallHomeViewController.h"
#import <XRCarouselView.h>
#import "MallsCollectionViewCell.h"
#import "AdsServer.h"
#import "Goods.h"
#import "MallDetailViewController.h"
//#import "MallClassificationViewController.h"

#import "SearchViewController.h"
#import "MallClassViewController.h"
#import "MKJShoppingCartViewController.h"
#import "MallLiveCollectionViewCell.h"
#import "UIViewController+KNSemiModal.h"

@interface MallInLiveViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;


@end

@implementation MallInLiveViewController {
    UIView          *_headBgView;
    UIButton        *_returnBtn;
    UIButton        *_shopCarBtn;
    UIButton        *_shopSpeciesBtn;
    XRCarouselView  *_carouselView;
    UIButton        *_recommendBtn;
    
    UICollectionView *_collectionView;
    MallsCollectionViewCell *_item;
    
    CGFloat         _collectionW;
    CGFloat         _collectionH;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.hidden = YES;         //默认隐藏，后台返回有数据才显示
    self.page = 1;
    
    [self GETMallsGoods];
    
    [self createUI];
    
    [self GETAds];
    
    [self refreshData];
}

#pragma mark ==========构建UI==========
- (void)createUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    // collectionView
    
    // 集合视图 collectionView所有布局的父类
    // 系统提供自带的布局类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 默认为纵向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    
    //改变view的大小和位置为右侧
    self.view.frame = CGRectMake(SCREEN_WIDTH-SCREEN_WIDTH/4, SH(5), SCREEN_WIDTH/4-20+5, SCREEN_HEIGHT-SH(5)*2);
	//橱窗加个标题
	UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 25)];
	[self.view addSubview:titleLabel];
	titleLabel.text = @"商品秒杀";
	titleLabel.textColor = kWhiteColor;
	titleLabel.font = [UIFont systemFontOfSize:14];
	titleLabel.textAlignment = NSTextAlignmentCenter;
	titleLabel.layer.borderWidth = 1;
	titleLabel.layer.borderColor = [UIMainColorRGB CGColor];
	titleLabel.backgroundColor = UIMainColorRGB;
	
    // 创建collectionView
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(3, titleLabel.y+titleLabel.height+10, SCREEN_WIDTH/4-20, self.view.height-titleLabel.height-40) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = UISeparatedColorRGB;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"MallLiveCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
    
    //flowLayout.headerReferenceSize = CGSizeMake(0, SW(5)*2+SW(12));
    //注册头视图
    /*
     [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
     */
    
    CGSize size1 = [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(10)];
    
    _collectionW = SCREEN_WIDTH/4-20-10;
    _collectionH = _collectionW+30;
	
	UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height-20, self.view.width, 20)];
	[self.view addSubview:bottomView];
	bottomView.backgroundColor = kWhiteColor;
	UIImageView *downImg = [[UIImageView alloc] initWithImage:IMAGE(@"arrow_down_date")];
	downImg.frame = CGRectMake(bottomView.width/2-10, 5, 15, 10);
	[bottomView addSubview:downImg];
	
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    _item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    
    _item.model = self.infoArr[indexPath.row];
    
    return _item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    NSLog(@"%f", _item.cover.height);
    //    return CGSizeMake((SCREEN_WIDTH-30)/2, _item.money.y+_item.money.height+10);
    return CGSizeMake(_collectionW, _collectionH);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 5, 10, 5);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"点击collectionView.item = %ld", indexPath.row);
    
    Goods *model = self.infoArr[indexPath.row];
    
    MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
    detailVC.goodId = model.goods_id;
    detailVC.isFromLive = 1;
    //detailVC.view.frame = CGRectMake(20, 20, 300, 500);
    //[self.navigationController pushViewController:detailVC animated:YES];
	detailVC.viewSizeH = SCREEN_HEIGHT*0.9;
	detailVC.viewSizeW = SCREEN_WIDTH*0.9;
	[self.delegate addChild:detailVC inRect:CGRectMake((SCREEN_WIDTH-detailVC.viewSizeW)/2, (SCREEN_HEIGHT-detailVC.viewSizeH)/2, detailVC.viewSizeW, detailVC.viewSizeH)];
}
//创建头视图
/*
 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
 viewForSupplementaryElementOfKind:(NSString *)kind
 atIndexPath:(NSIndexPath *)indexPath {
 
 UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
 [headView addSubview:_carouselView];
 [headView addSubview:_recommendBtn];
 headView.backgroundColor = kWhiteColor;
 
 return headView;
 }
 */


#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETMallsGoods];
    }];
    
}

#pragma mark ===========响应方法==========
- (void)GETMallsGoods {
    
    NSDictionary *param = @{
                            @"per_page":@"6",
                            @"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"uid":self.uidForMall
                            };
    
    [[NetworkTool sharedTool] requestWithName:@"获取商品" URLString:APIMallLiveGoods parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        
        for (NSDictionary *dic in arr) {
            Goods *model = [[Goods alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        if (self.infoArr.count != 0) {
            self.view.hidden = NO;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_collectionView.mj_footer endRefreshing];
            [_collectionView reloadData];
        });
        
    }];
}

// 获取广告
- (void)GETAds {
    
    [AdsServer GETAds:@{@"board":@"app_mall"} xrView:_carouselView];
    
}


// 返回
- (void)returnClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
// 进入商品分类
- (void)speciesClick:(UIButton *)sender {
    //        [self.navigationController pushViewController:[[MallClassificationViewController alloc] init] animated:YES];
    //    [self.navigationController pushViewController:[[MallClassViewController alloc] init] animated:YES];
}
// 进入购物车列表
- (void)cartClick:(UIButton *)sender {
    //    MallShopCartViewController *cartVC = [[MallShopCartViewController alloc] init];
    //    [self.navigationController pushViewController:cartVC animated:YES];
    MKJShoppingCartViewController *shop = [MKJShoppingCartViewController new];
    [self.navigationController pushViewController:shop animated:YES];
}

// 商品搜索
- (void)searchClicK:(id)sender {
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.type = 3;
    [self.navigationController pushViewController:searchVC animated:YES];
}


// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
